import React, { useState, useEffect, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  AlertTriangle,
  Lightbulb,
  RefreshCw,
  Plus,
  Trash2,
  Phone,
  MapPin,
  Hospital,
  Loader2,
  BookOpen,
  Badge,
} from "lucide-react";
import { InvokeLLM } from "@/api/integrations";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import EmergencyMeasureImportModal from "./EmergencyMeasureImportModal";
import { RecommendationsAPI } from "@/api/Recommendations";

export default function EmergencyPlanTab({
  scheme,
  onUpdate,
  emergencyMeasureTemplates = [],
}) {
  const [emergencyPlan, setEmergencyPlan] = useState("");
  const [emergencyContacts, setEmergencyContacts] = useState({
    hospital: { name: "", address: "", phone: "", directions: "" },
    fireDepartment: { name: "", address: "", phone: "", directions: "" },
    policeStation: { name: "", address: "", phone: "", directions: "" },
  });
  const [emergencyMeasures, setEmergencyMeasures] = useState([]);
  const [reportingProcess, setReportingProcess] = useState("");
  const [isGenerating, setIsGenerating] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [loadingRisks, setLoadingRisks] = useState(false);
  // 新增：推荐加载状态
  const [isRecommendLoading, setIsRecommendLoading] = useState(false);

  useEffect(() => {
    console.log("🔍 EmergencyPlanTab - 初始化数据:", scheme);
    setEmergencyPlan(scheme.emergencyPlan || "");
    setEmergencyContacts(
      scheme.emergencyContacts || {
        hospital: { name: "", address: "", phone: "", directions: "" },
        fireDepartment: { name: "", address: "", phone: "", directions: "" },
        policeStation: { name: "", address: "", phone: "", directions: "" },
      }
    );
    console.log(
      scheme.emergencyResponseMeasures,
      "scheme.emergencyResponseMeasures "
    );

    setEmergencyMeasures(scheme.emergencyResponseMeasures || []);
    setReportingProcess(scheme.emergencyReportingProcess || "");
  }, [scheme]);

  const generateEmergencyPlan = async () => {
    setIsGenerating(true);
    try {
      const prompt = `作为电力工程安全专家，请为以下施工方案生成专业的现场应急预案：

施工方法：${scheme.constructionMethod || "未指定"}
施工环境：${scheme.scopeOfWork || ""}
主要风险：${scheme.riskAssessment || ""}

请生成包含以下内容的应急预案：
1. 应急组织机构
2. 应急联系方式
3. 主要应急情况及处置措施
4. 应急物资配备
5. 信息报告程序

要求符合电力施工安全管理规定。`;

      const response = await InvokeLLM({
        prompt: prompt,
        addContextFromInternet: false,
      });

      setEmergencyPlan(response);
      updateScheme({ emergencyPlan: response });
    } catch (error) {
      console.error("生成应急预案失败:", error);
      alert("生成应急预案失败，请重试");
    } finally {
      setIsGenerating(false);
    }
  };

  // 新增：智能推荐报送流程
  const recommendReportingProcess = async () => {
    setIsRecommendLoading(true);
    try {
      // 调用推荐API，传递必要的方案信息作为上下文
      const response = await RecommendationsAPI.reportingProcess(scheme.id);
      // 填充返回的数据到输入框
      if (response && response.data) {
        setReportingProcess(response.data.emergencyReportingProcess);
        updateScheme({
          emergencyReportingProcess: response.data.emergencyReportingProcess,
        });
      } else {
        alert("未获取到有效的推荐内容，请尝试其他方式");
      }
    } catch (error) {
      console.error("获取报送流程推荐失败:", error);
      alert("获取推荐失败，请重试");
    } finally {
      setIsRecommendLoading(false);
    }
  };

  const updateScheme = (updates) => {
    console.log("🔍 EmergencyPlanTab - 更新方案:", updates);
    onUpdate(updates);
  };

  const handleContactUpdate = (contactType, field, value) => {
    const updatedContacts = {
      ...emergencyContacts,
      [contactType]: {
        ...emergencyContacts[contactType],
        [field]: value,
      },
    };
    setEmergencyContacts(updatedContacts);
    updateScheme({ emergencyContacts: updatedContacts });
  };

  const addEmergencyMeasure = () => {
    const newMeasure = {
      id: Date.now().toString(),
      incidentType: "",
      description: "",
      immediateActions: "",
      requiredEquipment: "",
      responsiblePersonRole: "",
      source: "手动添加",
    };
    const updatedMeasures = [...emergencyMeasures, newMeasure];
    setEmergencyMeasures(updatedMeasures);
    updateScheme({ emergencyResponseMeasures: updatedMeasures });
  };

  const updateEmergencyMeasure = (id, field, value) => {
    const updatedMeasures = emergencyMeasures.map((measure) =>
      measure.id === id ? { ...measure, [field]: value } : measure
    );
    setEmergencyMeasures(updatedMeasures);
    updateScheme({ emergencyResponseMeasures: updatedMeasures });
  };

  const handleImportMeasures = useCallback(
    (selectedMeasures) => {
      if (!selectedMeasures || selectedMeasures.length === 0) {
        return;
      }
      const importedMeasures = selectedMeasures.map((template) => ({
        id: `imported-${
          template.id || template.code
        }-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
        incidentType: template.incidentType || "",
        description: template.description || "",
        immediateActions: Array.isArray(template.immediateActions)
          ? template.immediateActions.join("\n")
          : template.immediateActions || "",
        requiredEquipment: template.requiredEquipment || "",
        responsiblePersonRole: template.responsiblePersonRole || "",
        source: "知识库导入",
        templateCode: template.code || template.id,
      }));

      const existingMeasures = new Set(
        emergencyMeasures.map((m) => `${m.incidentType}-${m.description}`)
      );

      const uniqueImportedMeasures = importedMeasures.filter(
        (m) => !existingMeasures.has(`${m.incidentType}-${m.description}`)
      );

      if (uniqueImportedMeasures.length > 0) {
        onUpdate({
          emergencyResponseMeasures: [
            ...emergencyMeasures,
            ...uniqueImportedMeasures,
          ],
        });
      }

      setShowImportModal(false);
    },
    [emergencyMeasures, onUpdate]
  );

  const removeEmergencyMeasure = (id) => {
    const updatedMeasures = emergencyMeasures.filter(
      (measure) => measure.id !== id
    );
    setEmergencyMeasures(updatedMeasures);
    updateScheme({ emergencyResponseMeasures: updatedMeasures });
  };

  const handleReportingProcessUpdate = (value) => {
    setReportingProcess(value);
    updateScheme({ emergencyReportingProcess: value });
  };

  const contactTypes = [
    {
      key: "hospital",
      label: "附近医院",
      icon: <Hospital className="w-5 h-5 text-red-600" />,
      color: "bg-red-50 border-red-200",
    },
    {
      key: "fireDepartment",
      label: "消防队",
      icon: <AlertTriangle className="w-5 h-5 text-orange-600" />,
      color: "bg-orange-50 border-orange-200",
    },
    {
      key: "policeStation",
      label: "派出所",
      icon: <Phone className="w-5 h-5 text-blue-600" />,
      color: "bg-blue-50 border-blue-200",
    },
  ];

  return (
    <div className="space-y-6">
      <Tabs defaultValue="emergency-contacts" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="emergency-contacts">应急联系人</TabsTrigger>
          <TabsTrigger value="emergency-measures">应急处置措施</TabsTrigger>
          <TabsTrigger value="reporting-process">报送流程</TabsTrigger>
        </TabsList>

        <TabsContent value="emergency-contacts">
          {/* 应急联系人内容保持不变 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Phone className="w-5 h-5 text-blue-600" />
                应急联系机构
              </CardTitle>
              <p className="text-sm text-gray-500">
                配置施工现场的应急联系机构信息，确保紧急情况下能快速联系相关部门。
              </p>
            </CardHeader>
            <CardContent>
              <div className="grid gap-6 md:grid-cols-1">
                {contactTypes.map((contactType) => (
                  <Card
                    key={contactType.key}
                    className={`${contactType.color} shadow-sm`}
                  >
                    <CardHeader className="pb-3">
                      <CardTitle className="text-base flex items-center gap-2">
                        {contactType.icon}
                        {contactType.label}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                          <Label
                            htmlFor={`${contactType.key}_name`}
                            className="text-sm"
                          >
                            机构名称
                          </Label>
                          <Input
                            id={`${contactType.key}_name`}
                            value={
                              emergencyContacts[contactType.key]?.name || ""
                            }
                            onChange={(e) =>
                              handleContactUpdate(
                                contactType.key,
                                "name",
                                e.target.value
                              )
                            }
                            placeholder="输入机构名称"
                          />
                        </div>
                        <div>
                          <Label
                            htmlFor={`${contactType.key}Phone`}
                            className="text-sm"
                          >
                            联系电话
                          </Label>
                          <Input
                            id={`${contactType.key}Phone`}
                            value={
                              emergencyContacts[contactType.key]?.phone || ""
                            }
                            onChange={(e) =>
                              handleContactUpdate(
                                contactType.key,
                                "phone",
                                e.target.value
                              )
                            }
                            placeholder="输入联系电话"
                          />
                        </div>
                      </div>
                      <div>
                        <Label
                          htmlFor={`${contactType.key}Address`}
                          className="text-sm"
                        >
                          详细地址
                        </Label>
                        <Input
                          id={`${contactType.key}Address`}
                          value={
                            emergencyContacts[contactType.key]?.address || ""
                          }
                          onChange={(e) =>
                            handleContactUpdate(
                              contactType.key,
                              "address",
                              e.target.value
                            )
                          }
                          placeholder="输入详细地址"
                        />
                      </div>
                      <div>
                        <Label
                          htmlFor={`${contactType.key}_directions`}
                          className="text-sm"
                        >
                          到达路线
                        </Label>
                        <Textarea
                          id={`${contactType.key}_directions`}
                          value={
                            emergencyContacts[contactType.key]?.directions || ""
                          }
                          onChange={(e) =>
                            handleContactUpdate(
                              contactType.key,
                              "directions",
                              e.target.value
                            )
                          }
                          placeholder="输入从施工现场到达该机构的具体路线"
                          rows={2}
                        />
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="emergency-measures">
          {/* 应急处置措施内容保持不变 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span className="flex items-center gap-2">
                  <AlertTriangle className="w-5 h-5 text-orange-600" />
                  应急处置措施
                </span>

                <div className="flex gap-2">
                  <Button
                    onClick={() => setShowImportModal(true)}
                    variant="outline"
                    size="sm"
                    disabled={loadingRisks}
                  >
                    {loadingRisks ? (
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    ) : (
                      <BookOpen className="w-4 h-4 mr-2" />
                    )}
                    从知识库导入
                  </Button>
                  <Button
                    onClick={addEmergencyMeasure}
                    variant="outline"
                    size="sm"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    添加处置措施
                  </Button>
                </div>
              </CardTitle>
              <p className="text-sm text-gray-500">
                制定针对不同紧急情况的具体处置措施和责任人。
              </p>
            </CardHeader>
            <CardContent>
              {emergencyMeasures.length === 0 ? (
                <div className="text-center py-8 border-2 border-dashed border-gray-200 rounded-lg">
                  <AlertTriangle className="w-12 h-12 mx-auto mb-2 text-gray-400" />
                  <p className="text-gray-500 mb-2">暂无应急处置措施</p>
                  <Button onClick={addEmergencyMeasure} variant="outline">
                    <Plus className="w-4 h-4 mr-2" />
                    添加第一个处置措施
                  </Button>
                </div>
              ) : (
                <div className="space-y-4">
                  {emergencyMeasures.map((measure, index) => (
                    <Card
                      key={measure.id}
                      className="border-orange-100 bg-orange-50/30"
                    >
                      <CardHeader className="pb-3 flex-row items-center justify-between">
                        <div className="flex items-center gap-2">
                          <CardTitle className="text-base">
                            处置措施 #{index + 1}
                          </CardTitle>
                          {measure.source || "手动添加"}
                        </div>
                        <Button
                          onClick={() => removeEmergencyMeasure(measure.id)}
                          variant="ghost"
                          size="sm"
                          className="text-red-500 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                          <div>
                            <Label className="text-sm">事故类型</Label>
                            <Input
                              value={measure.incidentType || ""}
                              onChange={(e) =>
                                updateEmergencyMeasure(
                                  measure.id,
                                  "incidentType",
                                  e.target.value
                                )
                              }
                              placeholder="如：高处坠落、触电事故等"
                            />
                          </div>
                          <div>
                            <Label className="text-sm">责任人</Label>
                            <Input
                              value={measure.responsiblePersonRole || ""}
                              onChange={(e) =>
                                updateEmergencyMeasure(
                                  measure.id,
                                  "responsiblePersonRole",
                                  e.target.value
                                )
                              }
                              placeholder="输入责任人姓名"
                            />
                          </div>
                        </div>
                        <div>
                          <Label className="text-sm">事故描述</Label>
                          <Textarea
                            value={measure.description || ""}
                            onChange={(e) =>
                              updateEmergencyMeasure(
                                measure.id,
                                "description",
                                e.target.value
                              )
                            }
                            placeholder="详细描述可能发生的事故情况"
                            rows={2}
                          />
                        </div>
                        <div>
                          <Label className="text-sm">立即处置措施</Label>
                          <Textarea
                            value={measure.immediateActions || ""}
                            onChange={(e) =>
                              updateEmergencyMeasure(
                                measure.id,
                                "immediateActions",
                                e.target.value
                              )
                            }
                            placeholder="发生事故后应立即采取的具体措施"
                            rows={3}
                          />
                        </div>
                        <div>
                          <Label className="text-sm">所需设备器材</Label>
                          <Input
                            value={measure.requiredEquipment || ""}
                            onChange={(e) =>
                              updateEmergencyMeasure(
                                measure.id,
                                "requiredEquipment",
                                e.target.value
                              )
                            }
                            placeholder="处置该类事故所需的设备和器材"
                          />
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="reporting-process">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span className="flex items-center gap-2">
                  <Phone className="w-5 h-5 text-green-600" />
                  应急信息报送流程
                </span>
                {/* 新增：智能推荐按钮 */}
                <Button
                  onClick={recommendReportingProcess}
                  disabled={isRecommendLoading}
                  variant="outline"
                  size="sm text-white bg-purple-600 hover:bg-purple-700 "
                >
                  {isRecommendLoading ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <Lightbulb className="w-4 h-4 mr-2" />
                  )}
                  智能推荐报送流程
                </Button>
              </CardTitle>
              <p className="text-sm text-gray-500">
                制定紧急情况下的信息报送流程，确保事故信息及时准确上报。
              </p>
            </CardHeader>
            <CardContent>
              <div>
                <Label
                  htmlFor="reportingProcess"
                  className="text-sm font-medium"
                >
                  报送流程详细说明
                </Label>
                <Textarea
                  id="reportingProcess"
                  value={reportingProcess}
                  onChange={(e) => handleReportingProcessUpdate(e.target.value)}
                  placeholder="请详细描述紧急情况下的信息报送流程，包括：&#10;1. 立即报告的联系人和方式&#10;2. 报告的时限要求&#10;3. 报告的内容要素&#10;4. 后续跟进报告的安排&#10;5. 涉及的部门和责任人"
                  rows={10}
                  className="mt-2"
                />
              </div>
              {reportingProcess.trim() === "" && (
                <div className="mt-4 p-4 border border-yellow-200 bg-yellow-50 rounded-lg">
                  <div className="flex items-start gap-3">
                    <AlertTriangle className="w-5 h-5 text-yellow-600 mt-0.5 flex-shrink-0" />
                    <div className="text-sm">
                      <p className="font-medium text-yellow-800">
                        建议包含以下内容：
                      </p>
                      <ul className="text-yellow-700 mt-2 space-y-1 list-disc list-inside">
                        <li>第一时间报告现场负责人和项目经理</li>
                        <li>根据事故等级决定是否需要报告上级单位</li>
                        <li>联系相关应急救援机构</li>
                        <li>按规定时限上报监管部门</li>
                        <li>做好事故记录和后续跟踪</li>
                      </ul>
                    </div>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
      <EmergencyMeasureImportModal
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        emergencyMeasureTemplates={emergencyMeasureTemplates}
        onImport={handleImportMeasures}
        existingMeasures={emergencyMeasures}
      />
    </div>
  );
}
